package helperx

import (
	"bufio"
	"bytes"
	"encoding/json"
	"errors"
	"sort"
	"strconv"

	jsoniter "github.com/json-iterator/go"
)

// StructToMapByJson 将一维的结构体struct转为字典map
// 仅支持int、float、string
func StructToMapByJson(obj interface{}) (map[string]string, error) {
	m := make(map[string]interface{})
	j, _ := jsoniter.Marshal(obj)
	json.Unmarshal(j, &m)

	res := make(map[string]string)
	for k, v := range m {
		switch t := v.(type) {
		case string:
			res[k] = t
		case int:
			res[k] = strconv.Itoa(t)
		case uint:
			res[k] = strconv.Itoa(int(t))
		case int16:
			res[k] = strconv.Itoa(int(t))
		case uint16:
			res[k] = strconv.Itoa(int(t))
		case int32:
			res[k] = strconv.Itoa(int(t))
		case uint32:
			res[k] = strconv.Itoa(int(t))
		case int64:
			res[k] = strconv.Itoa(int(t))
		case uint64:
			res[k] = strconv.Itoa(int(t))
		case float32:
			res[k] = strconv.FormatFloat(float64(t), 'f', -1, 64)
		case float64:
			res[k] = strconv.FormatFloat(t, 'f', -1, 64)
		default:
			return nil, errors.New("invalid value type")
		}
	}

	return res, nil
}

// MapSortToQueryString map按照key排序，输出拼接的query字符串
func MapSortToQueryString(m map[string]string) string {
	var keys []string
	for k := range m {
		keys = append(keys, k)
	}
	sort.Strings(keys)

	b := bytes.NewBuffer(make([]byte, 0))
	buf := bufio.NewWriter(b)

	for i, k := range keys {
		buf.Write([]byte(k))
		buf.Write([]byte("="))
		buf.Write([]byte(m[k]))

		if i < len(keys)-1 {
			buf.Write([]byte("&"))
		}
	}
	buf.Flush()

	return b.String()
}
